package treepro;

/**
 *
 * @author Ivan
 */
import java.awt.*;
import java.awt.geom.AffineTransform;
import javax.swing.*;
import java.awt.print.*;

public class PrintUtilities implements Printable {
    
    private Component componentToBePrinted;
    public static final double MM_TO_PAPER_UNITS = 1 / 25.4 * 72;
    public static double widthA4 = 210 * MM_TO_PAPER_UNITS;
    public static double heightA4 = 297 * MM_TO_PAPER_UNITS;
    public static double leftMargin = 4.0 * MM_TO_PAPER_UNITS;
    public static double topMargin = 4.0 * MM_TO_PAPER_UNITS;    
    
    public static void printComponent(Component c) {
        new PrintUtilities(c).print();
    }
    
    public PrintUtilities(Component componentToBePrinted) {
        this.componentToBePrinted = componentToBePrinted;
    }
    
    public void print() {
        PrinterJob printJob = PrinterJob.getPrinterJob();
        PageFormat pf = printJob.defaultPage();
        pf.setOrientation(PageFormat.LANDSCAPE);
        Paper paper = pf.getPaper();
        paper.setSize(widthA4, heightA4);
        paper.setImageableArea(leftMargin, topMargin, widthA4 - 2 * leftMargin, heightA4 - 2 * topMargin);
        pf.setPaper(paper);
        printJob.setCopies(1);
        Book book = new Book();
        book.append(this, pf);
        printJob.setPageable(book);
        if (printJob.printDialog()) {
            try {
                
                printJob.print();                
            } catch (PrinterException pe) {
                System.out.println("Error printing: " + pe);
            }
        }
    }
    
    public int print(Graphics g, PageFormat pageFormat, int pageIndex) {
        if (pageIndex > 0) {
            return (NO_SUCH_PAGE);
        } else {
            //componentToBePrinted.setBackground(Color.RED);
            Graphics2D g2d = (Graphics2D) g;
            double W = pageFormat.getImageableWidth();
            double H = pageFormat.getImageableHeight();
            double minX = pageFormat.getImageableX();
            double minY = pageFormat.getImageableY(); 
            g2d.transform(new AffineTransform((W)/componentToBePrinted.getWidth(),0,0,(H)/componentToBePrinted.getHeight(),minX,minY)); 
            //g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
            disableDoubleBuffering(componentToBePrinted);
            componentToBePrinted.print(g2d);
            enableDoubleBuffering(componentToBePrinted);
            return (PAGE_EXISTS);
        }
    }
    
    public static void disableDoubleBuffering(Component c) {
        RepaintManager currentManager = RepaintManager.currentManager(c);
        currentManager.setDoubleBufferingEnabled(false);
    }
    
    public static void enableDoubleBuffering(Component c) {
        RepaintManager currentManager = RepaintManager.currentManager(c);
        currentManager.setDoubleBufferingEnabled(true);
    }
}
